﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using EdexApiClient;


namespace HQC2EDEX
{
    public partial class Service1 : ServiceBase
    {
        private Timer timer = null;

        public Service1()
        {
            InitializeComponent();
            try
            {
                if (!EventLog.SourceExists(this.ServiceName + "_log"))
                    EventLog.CreateEventSource(this.ServiceName, this.ServiceName + "_log");
            }
            catch { }
            serviceLog.Source = this.ServiceName + "_log";
            serviceLog.Log = this.ServiceName + "_log";
        }

        protected override void OnStart(string[] args)
        {
            serviceLog.WriteEntry(this.ServiceName + " запущен");
            Properties.Settings.Default.Reload();
            var ExecuteTimes = Properties.Settings.Default.ExecuteTimes;
            if (Properties.Settings.Default.ExecuteImmediately)
                ExecuteTimes.Add(DateTime.Now.AddMinutes(1).ToString("HH:mm"));

            timer = new Timer();
            timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
            timer.Interval = TimerUtil.GetNewTimerInterval(ExecuteTimes);
            timer.Enabled = true;
        }

        protected override void OnStop()
        {
            serviceLog.WriteEntry(this.ServiceName + " остановлен");
            timer.Stop();
            timer.Close();
        }

        /// <summary>
        /// При срабатывании таймера
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void OnElapsedTime(object source, ElapsedEventArgs e)
        {
            // Останавливаем таймей и стартуем выполнение выгрузки
            timer.Stop();
            Process();
            // Интервал таймера
            Properties.Settings.Default.Reload();
            timer.Interval = TimerUtil.GetNewTimerInterval(Properties.Settings.Default.ExecuteTimes);
            timer.Start();
        }

        private void Process()
        {
            try
            {
                serviceLog.WriteEntry("Запуск процедуры загрузки справочников ТНК");
                Properties.Settings.Default.Reload();
                string ApiURI = Properties.Settings.Default.ApiUri;
                string RootUri = Properties.Settings.Default.RootUri;
                string login = Properties.Settings.Default.LOGIN;
                string password = Properties.Settings.Default.PASSWORD;
                string TnkKey = Properties.Settings.Default.TNKKey;
                string IBSConnectionString = Properties.Settings.Default.IBSConnectionString;
                string HQCConnectionString = Properties.Settings.Default.HQCConnectionString;
                string UserMailAddress = Properties.Settings.Default.UserMailAddress;
                string ServiceMailAddress = Properties.Settings.Default.ServiceMailAddress;
                DateTime LastSyncDateSupplers = Properties.Settings.Default.LastSyncDateSuppliers;
                DateTime LastSyncDateItems = Properties.Settings.Default.LastSyncDateItems;
                DateTime LastSyncDateSites = Properties.Settings.Default.LastSyncDateSites; 
                
                var edex = new EdexApiClient.EdexApiContext(ApiURI, RootUri, login, password);
                edex.ChangeCompany(TnkKey); 
                var ibs = new IBS.IbsDataContext(IBSConnectionString);
                var hqc = new HQC.HqcDataContext(HQCConnectionString);
                   
                //загрузка поставщиков
                try
                {
                    serviceLog.WriteEntry("Загрузка справочника поставщиков");     
                    var LastSyncDate = ibs.GetLastSyncDate("LastSyncDateTNK_Suppliers");
                    LastSyncDate = LastSyncDate > LastSyncDateSupplers ? LastSyncDate : LastSyncDateSupplers;              
                    var suppliers = hqc.GetSuppliers(LastSyncDate).ToList();
                    if (suppliers.Count > 0)
                    {
                        var existingSuppliers = edex.GetSuppliers();
                        foreach (var supplier in suppliers)
                        {
                            EdexApiClient.WH_COMPANIES sup = new EdexApiClient.WH_COMPANIES()
                            {
                                EXT_KEY = supplier.ID_Record.ToString(),
                                COMPANY_NAME = supplier.SupplierName
                            };

                            if (existingSuppliers.Where(r => r.EXT_KEY == sup.EXT_KEY).Any())
                            {
                                sup.GUID_RECORD = existingSuppliers.Where(r => r.EXT_KEY == sup.EXT_KEY).FirstOrDefault().GUID_RECORD;
                                edex.UpdateSupplier(sup);
                            }
                            else
                                edex.AddSupplier(sup);
                        }
                    }
                    ibs.SetLastSyncDate(DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss"), "LastSyncDateTNK_Suppliers");
                }
                catch (Exception ex)
                {
                    serviceLog.WriteEntry(String.Format("При загрузке справочника поставщиков произошла ошибка:\nMessage = '{0}'\nInnerException = '{1}'\nSource = '{2}'\n", ex.Message, ex.InnerException, ex.Source), EventLogEntryType.Error);     
                }

                //загрузка товара
                try
                {
                    serviceLog.WriteEntry("Загрузка справочника товара");
                    var LastSyncDate = ibs.GetLastSyncDate("LastSyncDateTNK_Items");
                    LastSyncDate = LastSyncDate > LastSyncDateItems ? LastSyncDate : LastSyncDateItems;  
                    var items = hqc.GetItems(LastSyncDate).ToList();
                    if (items.Count > 0)
                    {
                        var existingItems = edex.GetItems();
                        foreach (var item in items)
                        {
                            EdexApiClient.WH_ITEMS itm = new EdexApiClient.WH_ITEMS()
                            {
                                EXT_KEY = item.ID_Record.ToString(),
                                ITEM_NAME = item.ItemName
                            };

                            if (existingItems.Where(r => r.EXT_KEY == itm.EXT_KEY).Any())
                            {
                                itm.GUID_RECORD = existingItems.Where(r => r.EXT_KEY == itm.EXT_KEY).FirstOrDefault().GUID_RECORD;
                                edex.UpdateItem(itm);
                            }
                            else
                                edex.AddItem(itm);
                        }
                    }
                    ibs.SetLastSyncDate(DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss"), "LastSyncDateTNK_Items");
                }
                catch (Exception ex)
                {
                    serviceLog.WriteEntry(String.Format("При загрузке справочника товара произошла ошибка:\nMessage = '{0}'\nInnerException = '{1}'\nSource = '{2}'\n", ex.Message, ex.InnerException, ex.Source), EventLogEntryType.Error);
                }

                //загрузка станций
                try
                {
                    serviceLog.WriteEntry("Загрузка справочника станций");
                    var LastSyncDate = ibs.GetLastSyncDate("LastSyncDateTNK_Sites");
                    LastSyncDate = LastSyncDate > LastSyncDateSites ? LastSyncDate : LastSyncDateSites; 
                    var sites = hqc.GetSites(LastSyncDate).ToList();
                    if (sites.Count > 0)
                    {
                        var existingsites = edex.GetLocations();
                        foreach (var site in sites)
                        {
                            EdexApiClient.WH_LOCATIONS loc = new EdexApiClient.WH_LOCATIONS()
                            {
                                EXT_KEY = site.ID_Record.ToString(),
                                LOCATION_NAME = site.LocationName,
                                STREET = site.Address,
                                IS_DEFAULT = false
                            };

                            if (existingsites.Where(r => r.EXT_KEY == loc.EXT_KEY).Any())
                            {
                                loc.GUID_RECORD = existingsites.Where(r => r.EXT_KEY == loc.EXT_KEY).FirstOrDefault().GUID_RECORD;
                                edex.UpdateLocation(loc);
                            }
                            else
                                edex.AddLocation(loc);
                        }
                    }
                    ibs.SetLastSyncDate(DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss"), "LastSyncDateTNK_Sites");

                }
                catch (Exception ex)
                {
                    serviceLog.WriteEntry(String.Format("При загрузке справочника станций произошла ошибка:\nMessage = '{0}'\nInnerException = '{1}'\nSource = '{2}'\n", ex.Message, ex.InnerException, ex.Source), EventLogEntryType.Error);
                }

            }
            catch (Exception ex)
            {
                serviceLog.WriteEntry(String.Format("В процедуре загрузки справочников произошла ошибка:\nMessage = '{0}'\nInnerException = '{1}'\nSource = '{2}'\n", ex.Message, ex.InnerException, ex.Source), EventLogEntryType.Error);
            }


            serviceLog.WriteEntry("Процедуры загрузки справочников ТНК завершена");
        }

    }
}
